package zhuzx.generator;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.util.HashSet;
import java.util.Set;

import javax.swing.JOptionPane;

import org.zhuzx.util.GeneralUtil;
import org.zhuzx.util.JdbcUtil;
import org.zhuzx.util.MicroUtil;

/**
 * class生成器，三个关联的配置文件：
 * db.properties配置数据库连接；
 * JavaTypes.properties配置JDBC类型（来自java.sql.Types中的常量名）到Java类型的映射；
 * SqlFunction.properties配置SQL函数的注释（需要灵活配置）。
 * @author	zhuzx	2016年4月19日
 */
public class ClassCreator {
	
	private static String packageName = ClassCreator.class.getPackage().getName();
	private static String packagePath = packageName.replaceAll("\\.", "\\"+File.separator) + File.separator;
	private static final Set<String> needInport;

	static {
		needInport = new HashSet<>();
		for (String type : DatabaseMetadataUtil.types.values()) {
			if (!GeneralUtil.isBlank(type) && type.indexOf('.')>-1) {
				needInport.add(type);
			}
		}
		needInport.add("java.math.BigInteger");
	}
	
	
	public static void main(String[] args) throws Exception {
		String inputValue = JOptionPane.showInputDialog("请输入sql语句或者表名：");
		Connection conn = JdbcUtil.getDbConn(null);
		inputValue = inputValue.trim();
		String[][] columns;
		if (inputValue.indexOf(" ") == -1) {
			columns = SqlTextParser.getMetaData(conn, inputValue);
		} else {
			columns = SqlTextParser.getColumns(conn, inputValue);
		}
		conn.close();
		
		String className = JOptionPane.showInputDialog("输入类名：");
		className = GeneralUtil.isBlank(className) ? "TempClass" : className;
		className = MicroUtil.capitalizeTheFirstChar(className);
		String src = createClassSource(columns, className);
		String[] options = new String[]{"复制到剪贴板", "生成Java类文件"};
		int selected = JOptionPane.showOptionDialog(null, "请选择操作：", "生成器",
				JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null,
				options, options[0]);
		if (selected == 0) {
			Toolkit toolkit = Toolkit.getDefaultToolkit();
			Clipboard clipboard = toolkit.getSystemClipboard();
			StringSelection ss = new StringSelection(src);
			clipboard.setContents(ss, null);
			System.out.println(src);
		} else {
			String outputPath = System.getProperty("user.dir") + File.separator + "src" +
					File.separator + packagePath;
			File file = new File(outputPath + className + ".java");
			if (!file.exists()) {
				String mavenPath = "src\\" + File.separator + "main\\" + File.separator + "java";
				outputPath = outputPath.replaceFirst("\\bsrc\\b", mavenPath);
				file = new File(outputPath + className + ".java");
			}
			DataOutputStream out = new DataOutputStream(
					new BufferedOutputStream(new FileOutputStream(file)));
			out.write(src.getBytes());
			out.close();
		}
	}
	
	/**
	 * 生成类的源码
	 * @param columns 由字段信息组成的二维数组，每个子数组对应一个字段，其中有四个元素：字段名，类型，长度，注释。
	 * @param className 指定的类名
	 */
	public static String createClassSource(String[][] columns, String className) {
		for (int i=0; i<columns.length; i++) {
			columns[i][0] = MicroUtil.convertUnderlineToCamelCased(columns[i][0]);
		}
		StringBuilder src = ClassSourceCodeUtil.createSimpleCode(columns, className);
		String beautifier = src.toString();
		Set<String> contained = new HashSet<String>();
		for (String impo : needInport) {
			if (src.indexOf(" " + impo + " ") > -1) {
				beautifier = beautifier.replaceAll(impo, impo.substring(impo.lastIndexOf(".")+1));
				contained.add(impo);
			}
		}
		src.setLength(0);
		src.append("package " + packageName + ";\n\n");
		for (String impo : contained) {
			src.append("import " + impo + ";\n");
		}
		src.append("\n" + beautifier);
		return src.toString();
	}
	
}